package com.knowif.backend.controller;

import com.github.pagehelper.PageInfo;
import com.knowif.backend.service.UserOrderService;
import com.knowif.pojo.UserOrder;
import com.knowif.search.SearchCondition;
import com.knowif.system.model.RestBean;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author ：Xh
 * @date ：Created in 2019/6/9 0009 20:12
 */
@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private UserOrderService userOrderService;

    /**
     * 订单筛选
     * @param searchCondition
     * @return
     */
    @PostMapping("/screen")
    public RestBean<?> screen(@RequestBody SearchCondition searchCondition){
        Map<String,Object> params = searchCondition.getParameterMap();
        if(params.containsKey("price")){
            try {
                Double price = (Double.parseDouble((String) params.get("price")));
                params.put("price", price);
            } catch (NumberFormatException e) {
                return RestBean.buildError("请输入正确金额格式");
            }
        }

        PageInfo<UserOrder> info = userOrderService.screen(params, searchCondition.getPageNumber(), searchCondition.getPageSize());
        return RestBean.build(RestBean.success_code, "", info);
    }

    /**
     * 导出订单
     * @param searchCondition
     * @param response
     */
    @PostMapping("/export")
    public void export(@RequestBody SearchCondition searchCondition, HttpServletResponse response){
        Map<String,Object> params = searchCondition.getParameterMap();
        PageInfo<?> screen = userOrderService.screen(params, 0, 99999);
        @SuppressWarnings("unchecked")
		List<UserOrder> list = (List<UserOrder>) screen.getList();

        // 第一步，创建一个HSSFWorkbook，对应一个Excel文件
        HSSFWorkbook wb = new HSSFWorkbook();

        // 第二步，在workbook中添加一个sheet,对应Excel文件中的sheet
        HSSFSheet sheet = wb.createSheet();

        // 第三步，在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制
        HSSFRow row = sheet.createRow(0);

        // 第四步，创建单元格，并设置值表头 设置表头居中
        HSSFCellStyle style = wb.createCellStyle();
        style.setAlignment(HorizontalAlignment.CENTER);// 创建一个居中格式

        //声明列对象
        HSSFCell cell = null;

        String[] title = {"订单编号","学员手机号","导师姓名","咨询问题","订单金额","订单状态","下单时间"};

        //创建标题
        for(int i=0;i<title.length;i++){
            cell = row.createCell(i);
            cell.setCellValue(title[i]);
            cell.setCellStyle(style);
        }

        //创建内容
        for(int i=0;i<list.size();i++){
            UserOrder userOrder = list.get(i);
            row = sheet.createRow(i + 1);
            String wechatTradeNo = "";
            if( userOrder.getUserOrderFlows() != null &&   userOrder.getUserOrderFlows().size() > 0){
                wechatTradeNo = userOrder.getUserOrderFlows().get(0).getWechatTradeNo();
            }
            row.createCell(0).setCellValue(wechatTradeNo);
            row.createCell(1).setCellValue(userOrder.gettUser() == null ? "" : userOrder.gettUser().getPhoneNum());
            row.createCell(2).setCellValue(userOrder.getTutorInfo() == null ? "" : userOrder.getTutorInfo().gettUser().getFullName());
            row.createCell(3).setCellValue(userOrder.getQuestion());
            row.createCell(4).setCellValue(userOrder.getPrice());
            row.createCell(5).setCellValue(userOrder.getStatus() == 1 ? "未支付" : (userOrder.getStatus() == 2 ? "已支付" : (userOrder.getStatus() == 3 ? "失效订单" : (userOrder.getStatus() == 4 ? "导师接单" : (userOrder.getStatus() == 5 ? "已交易" :
                    (userOrder.getStatus() == 6 ? "取消订单" : (userOrder.getStatus() == 7 ? "退款订单" : (userOrder.getStatus() == 8 ? "待评价" : (userOrder.getStatus() == 9 ? "评论完成" : null)))))))) );
            String createTime = "";
            if(userOrder.getUserOrderStatuses().get(0) != null){
                Date date = userOrder.getUserOrderStatuses().get(0).getCreateTime();
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                createTime = simpleDateFormat.format(date);
            }
            row.createCell(6).setCellValue(createTime);
        }
        try {
            String fileName = new String("订单".getBytes(),"ISO8859-1");
            response.setContentType("application/octet-stream;charset=ISO8859-1");
            response.setHeader("Content-Disposition", "attachment;filename="+ fileName);
            response.addHeader("Pargam", "no-cache");
            response.addHeader("Cache-Control", "no-cache");
            OutputStream os = response.getOutputStream();
            wb.write(os);
            os.flush();
            os.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 订单状态详情
     * @param userOrderId
     * @return
     */
    @GetMapping("/detail/{userOrderId}")
    public RestBean<?> query(@PathVariable("userOrderId") int userOrderId){
        return RestBean.buildSuccess(userOrderService.selectOrderStatus(userOrderId));
    }
}
